我们将介绍最简单的存储形式：“缓冲”存储，它只涉及保留所有先前的消息的缓冲区。我们将展示如何在这里使用模块化实用函数，然后展示它如何在链中使用（返回字符串以及消息列表）。

## 聊天消息历史 (ChatMessageHistory)

大多数（如果不是全部）内存模块的核心实用类之一是 `ChatMessageHistory` 类。这是一个超轻量级的包装器，它公开了方便的方法来保存人类消息、AI 消息，然后获取它们全部。

如果您在链外管理内存，可能需要直接使用此类。

<!-- 警告：此文件是自动生成的！请勿编辑！请改为编辑具有与此文件相同位置和名称的笔记本。 -->


```python
from langchain.memory import ChatMessageHistory

history = ChatMessageHistory()

history.add_user_message("hi!")

history.add_ai_message("whats up?")
```


```python
history.messages
```

<CodeOutputBlock lang="python">

```
    [HumanMessage(content='hi!', additional_kwargs={}),
     AIMessage(content='whats up?', additional_kwargs={})]
```

</CodeOutputBlock>

## ConversationBufferMemory

现在我们展示如何在链中使用这个简单的概念。我们首先展示 `ConversationBufferMemory`，它只是 ChatMessageHistory 的一个包装器，可以提取变量中的消息。

我们可以首先将其提取为字符串。


```python
from langchain.memory import ConversationBufferMemory
```


```python
memory = ConversationBufferMemory()
memory.chat_memory.add_user_message("hi!")
memory.chat_memory.add_ai_message("whats up?")
```


```python
memory.load_memory_variables({})
```

<CodeOutputBlock lang="python">

```
    {'history': 'Human: hi!\nAI: whats up?'}
```

</CodeOutputBlock>

我们还可以将历史记录作为消息列表获取


```python
memory = ConversationBufferMemory(return_messages=True)
memory.chat_memory.add_user_message("hi!")
memory.chat_memory.add_ai_message("whats up?")
```


```python
memory.load_memory_variables({})
```

<CodeOutputBlock lang="python">

```
    {'history': [HumanMessage(content='hi!', additional_kwargs={}),
      AIMessage(content='whats up?', additional_kwargs={})]}
```

</CodeOutputBlock>

## Using in a chain
Finally, let's take a look at using this in a chain (setting `verbose=True` so we can see the prompt).


```python
from langchain.llms import OpenAI
from langchain.chains import ConversationChain


llm = OpenAI(temperature=0)
conversation = ConversationChain(
    llm=llm,
    verbose=True,
    memory=ConversationBufferMemory()
)
```


```python
conversation.predict(input="Hi there!")
```

<CodeOutputBlock lang="python">

```


    > Entering new ConversationChain chain...
    Prompt after formatting:
    The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.

    Current conversation:

    Human: Hi there!
    AI:

    > Finished chain.





    " Hi there! It's nice to meet you. How can I help you today?"
```

</CodeOutputBlock>


```python
conversation.predict(input="I'm doing well! Just having a conversation with an AI.")
```

<CodeOutputBlock lang="python">

```


    > Entering new ConversationChain chain...
    Prompt after formatting:
    The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.

    Current conversation:
    Human: Hi there!
    AI:  Hi there! It's nice to meet you. How can I help you today?
    Human: I'm doing well! Just having a conversation with an AI.
    AI:

    > Finished chain.





    " That's great! It's always nice to have a conversation with someone new. What would you like to talk about?"
```

</CodeOutputBlock>


```python
conversation.predict(input="Tell me about yourself.")
```

<CodeOutputBlock lang="python">

```


    > Entering new ConversationChain chain...
    Prompt after formatting:
    The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.

    Current conversation:
    Human: Hi there!
    AI:  Hi there! It's nice to meet you. How can I help you today?
    Human: I'm doing well! Just having a conversation with an AI.
    AI:  That's great! It's always nice to have a conversation with someone new. What would you like to talk about?
    Human: Tell me about yourself.
    AI:

    > Finished chain.





    " Sure! I'm an AI created to help people with their everyday tasks. I'm programmed to understand natural language and provide helpful information. I'm also constantly learning and updating my knowledge base so I can provide more accurate and helpful answers."
```

</CodeOutputBlock>

## 保存消息历史

您经常需要保存消息，然后加载它们以便再次使用。这可以通过先将消息转换为普通的 Python 字典，保存这些字典（如 json 或其他格式），然后加载它们来轻松完成。以下是一个示例。


```python
import json

from langchain.memory import ChatMessageHistory
from langchain.schema import messages_from_dict, messages_to_dict

history = ChatMessageHistory()

history.add_user_message("hi!")

history.add_ai_message("whats up?")
```


```python
dicts = messages_to_dict(history.messages)
```


```python
dicts
```

<CodeOutputBlock lang="python">

```
    [{'type': 'human', 'data': {'content': 'hi!', 'additional_kwargs': {}}},
     {'type': 'ai', 'data': {'content': 'whats up?', 'additional_kwargs': {}}}]
```

</CodeOutputBlock>


```python
new_messages = messages_from_dict(dicts)
```


```python
new_messages
```

<CodeOutputBlock lang="python">

```
    [HumanMessage(content='hi!', additional_kwargs={}),
     AIMessage(content='whats up?', additional_kwargs={})]
```

</CodeOutputBlock>

这就是入门的全部内容！有许多不同类型的内存，请查看我们的示例以了解全部内容
